package com.aurora.demo.service;

import com.aurora.demo.repository.ThumbRepository;
import com.aurora.demo.entity.Thumb;
import com.aurora.demo.util.ImageUtil;
import org.bson.types.Binary;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@Service
public class ThumbService {

    @Autowired
    private ThumbRepository thumbRepository;

    @Autowired
    private RedisTemplate redisTemplate;

    public List<Thumb> findByName(List<String> names) {

        List<Thumb> thumbs = new ArrayList<>();
        for(String name : names) {
            Thumb thumb;
            //若redis缓存中包含此图片，直接返回
            if(redisTemplate.opsForHash().hasKey("thumb", name)) {
                thumb = (Thumb) redisTemplate.opsForHash().get("thumb", name);
            } else {
                //若redis缓存不包含此图片，从数据库中查询，并加入缓存
                thumb = thumbRepository.findByName(name);
                redisTemplate.opsForHash().put("thumb", name, thumb);
            }
            thumbs.add(thumb);
        }
        return thumbs;
    }

    public void save(MultipartFile file) {
        String name = file.getOriginalFilename().substring(0, 13);
        try {
            byte[] souceBytes = file.getBytes();
            BufferedImage source = ImageUtil.bytesToImage(souceBytes);
            BufferedImage target = ImageUtil.generateThumb(source, 75,75, false);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(target, "bmp", outputStream);
            byte [] targetBytes = ImageUtil.imageToBytes(target, "bmp");

            Thumb thumb = new Thumb();
            thumb.setName(name);
            thumb.setThumb(new Binary(targetBytes));
            thumbRepository.save(thumb);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public List<Thumb> findById(List<ObjectId> ids) {
        List<Thumb> thumbs = new ArrayList<>();
        for(ObjectId id : ids) {
            System.out.println(id.toString());
            thumbs.add(thumbRepository.findById(id.toString()).get());
        }
        return thumbs;
    }
}
